package wetalk.software.bupt.com.wetalk.application;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.listener.FindListener;
import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.listener.EventListener;
import wetalk.software.bupt.com.wetalk.listener.OnReceiveListener;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkConstant;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkMsg;
import wetalk.software.bupt.com.wetalk.util.CollectionUtils;
import wetalk.software.bupt.com.wetalk.util.CommonUtils;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.util.WeTalkJsonUtil;
import wetalk.software.bupt.com.wetalk.util.WeTalkLog;
import wetalk.software.bupt.com.wetalk.view.activity.MainActivity;
import wetalk.software.bupt.com.wetalk.view.activity.NewFriendsActivity;


/**
 * 推送消息接收器
 * @ClassName: MyMessageReceiver
 * @Description: TODO
 * @author smile
 * @date 2014-5-30 下午4:01:13
 */
public class MessageReceiver extends BroadcastReceiver {

	// 事件监听
	public static ArrayList<EventListener> ehList = new ArrayList<EventListener>();

	public static final int NOTIFY_ID = 0x000;
	public static int mNewNum = 0;//
	UserManager userManager;
	ChatUser currentUser;


	@Override
	public void onReceive(Context context, Intent intent) {
		String json = intent.getStringExtra("msg");
		String tag=intent.getStringExtra("msgType");
		String from=intent.getStringExtra("msgFrom");
		WeTalkLog.i("收到的message = " + json);

		/*userManager = UserManager.getInstance(context);
		currentUser = userManager.getCurrentUser();*/
		boolean isNetConnected = CommonUtils.isNetworkAvailable(context);
		if(isNetConnected){
			if (from.equals("sys_check")&&json.contains("success")){
				Toast.makeText(context,"已成功连接服务器",Toast.LENGTH_SHORT).show();
			}
			parseMessage(context, json,tag);
		}else{
			for (int i = 0; i < ehList.size(); i++)
				ehList.get(i).onNetChange(isNetConnected);
		}
	}

	/** 解析Json字符串
	 * @Title: parseMessage
	 * @Description: TODO
	 * @param @param context
	 * @param @param json
	 * @return void
	 * @throws
	 */

	private void parseMessage(final Context context, String json, final String tag) {
		JSONObject jo;
		currentUser=UserManager.getInstance(context).getCurrentUser();
		try {
			jo = new JSONObject(json);
			//String tag = WeTalkJsonUtil.getString(jo, WeTalkConstant.PUSH_KEY_TAG);
			if(tag.equals(WeTalkConfig.TAG_OFFLINE)){//下线通知
				if(currentUser!=null){
					if (ehList.size() > 0) {// 有监听的时候，传递下去
						for (EventListener handler : ehList)
							handler.onOffline();
					}else{
						//清空数据
						CustomApplication.getInstance().logout();
					}
				}
			}else{
				String fromId = WeTalkJsonUtil.getString(jo, WeTalkConstant.PUSH_KEY_TARGETID);
				//增加消息接收方的ObjectId--目的是解决多账户登陆同一设备时，无法接收到非当前登陆用户的消息。
				final String toId = WeTalkJsonUtil.getString(jo, WeTalkConstant.PUSH_KEY_TOID);
				String msgTime = WeTalkJsonUtil.getString(jo, WeTalkConstant.PUSH_READED_MSGTIME);
				switch (tag) {
					case "msg": //msg表示普通消息
						ChatManager.getInstance(context).createReceiveMsg(json,tag, new OnReceiveListener() {
							@Override
							public void onSuccess(WeTalkMsg msg) {
								if (currentUser != null && currentUser.getUserID().equals(toId)) {//当前登陆用户存在并且也等于接收方id
									mNewNum++;
									showMsgNotify(context, msg,tag);
								}
								if (ehList.size() > 0) {// 有监听的时候，传递下去
									for (int i = 0; i < ehList.size(); i++) {
										ehList.get(i).onMessage(msg);
									}
								}
							}

							@Override
							public void onFailure(int code, String arg1) {
								WeTalkLog.i("获取接收的消息失败：" + arg1);
							}
						});
						break;
					case "msg_pic":
						ChatManager.getInstance(context).createReceiveMsg(json,tag, new OnReceiveListener() {
							@Override
							public void onSuccess(WeTalkMsg msg) {
								if (ehList.size() > 0) {// 有监听的时候，传递下去
									for (int i = 0; i < ehList.size(); i++) {
										ehList.get(i).onMessage(msg);
									}
								}
								if (currentUser != null && currentUser.getUserID().equals(toId)) {//当前登陆用户存在并且也等于接收方id
									mNewNum++;
									showMsgNotify(context, msg,tag);
								}
							}

							@Override
							public void onFailure(int code, String arg1) {
								WeTalkLog.i("获取接收的消息失败：" + arg1);
							}
						});
						break;
					case "msg_voice":
						ChatManager.getInstance(context).createReceiveMsg(json,tag, new OnReceiveListener() {
							@Override
							public void onSuccess(WeTalkMsg msg) {
								if (ehList.size() > 0) {// 有监听的时候，传递下去
									for (int i = 0; i < ehList.size(); i++) {
										ehList.get(i).onMessage(msg);
									}
								}
								if (currentUser != null && currentUser.getUserID().equals(toId)) {//当前登陆用户存在并且也等于接收方id
									mNewNum++;
									showMsgNotify(context, msg,tag);
								}
							}

							@Override
							public void onFailure(int code, String arg1) {
								WeTalkLog.i("获取接收的消息失败：" + arg1);
							}
						});
						break;
					case "msg_file":
						ChatManager.getInstance(context).createReceiveMsg(json,tag, new OnReceiveListener() {
							@Override
							public void onSuccess(WeTalkMsg msg) {
								if (ehList.size() > 0) {// 有监听的时候，传递下去
									for (int i = 0; i < ehList.size(); i++) {
										ehList.get(i).onMessage(msg);
									}
								}
								if (currentUser != null && currentUser.getUserID().equals(toId)) {//当前登陆用户存在并且也等于接收方id
									mNewNum++;
									showMsgNotify(context, msg,tag);
								}
							}

							@Override
							public void onFailure(int code, String arg1) {
								WeTalkLog.i("获取接收的消息失败：" + arg1);
							}
						});
						break;
					case WeTalkConfig.TAG_ADD_CONTACT:
						//保存好友请求道本地，并更新后台的未读字段
						WeTalkInvitation message = ChatManager.getInstance(context).saveReceiveInvite(json, toId);
						if (currentUser != null) {//有登陆用户
							if (toId.equals(currentUser.getUserID())) {
								if (ehList.size() > 0) {// 有监听的时候，传递下去
									for (EventListener handler : ehList)
										handler.onAddUser(message);
								} else {
									showOtherNotify(context, message.getFromname(), toId, message.getFromname() + "请求添加好友", NewFriendsActivity.class);
								}
							}
						}
						break;
					case WeTalkConfig.TAG_ADD_AGREE:
						String username = WeTalkJsonUtil.getString(jo, WeTalkConstant.PUSH_KEY_TARGETUSERNAME);
						//收到对方的同意请求之后，就得添加对方为好友--已默认添加同意方为好友，并保存到本地好友数据库
						UserManager.getInstance(context).addContactAfterAgree(username, new FindListener<ChatUser>() {

							@Override
							public void onError(int arg0, final String arg1) {
							}

							@Override
							public void onSuccess(List<ChatUser> arg0) {
								//保存到内存中
								CustomApplication.getInstance().setContactList(CollectionUtils.list2map(WeTalkDB.create(context).getContactList()));
							}
						});
						//显示通知
						showOtherNotify(context, username, toId, username + "同意添加您为好友", MainActivity.class);
						//创建一个临时验证会话--用于在会话界面形成初始会话
						WeTalkMsg.createAndSaveRecentAfterAgree(context, json);
						break;
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			//这里截取到的有可能是web后台推送给客户端的消息，也有可能是开发者自定义发送的消息，需要开发者自行解析和处理
			WeTalkLog.i("parseMessage错误："+e.getMessage());
		}
	}

	/**
	 *  显示与聊天消息的通知
	 * @Title: showNotify
	 * @return void
	 * @throws
	 */
	public void showMsgNotify(Context context, WeTalkMsg msg,String msgType) {
		// 更新通知栏
		int icon = R.drawable.ic_launcher;
		String trueMsg = "";
		if(msgType.equals("msg")  && msg.getContent().contains("\\ue")){
			trueMsg = "[表情]";
		}else if(msgType.equals("msg_pic")){
			trueMsg = "[图片]";
		}else if(msgType.equals("msg_file")){
			trueMsg = "[文件]";
		}else{
			trueMsg = msg.getContent();
		}
		CharSequence tickerText = msg.getBelongUsername() + ":" + trueMsg;
		String contentTitle = msg.getBelongUsername()+ " (" + mNewNum + "条新消息)";

		Intent intent = new Intent(context, MainActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

		/*boolean isAllowVoice = CustomApplication.getInstance().getSpUtil().isAllowVoice();
		boolean isAllowVibrate = CustomApplication.getInstance().getSpUtil().isAllowVibrate();*/

		WeTalkNotifyManager.getInstance(context).showNotifyWithExtras(true,true,icon, tickerText.toString(), contentTitle, tickerText.toString(),intent);
	}


	/** 显示其他Tag的通知
	 * showOtherNotify
	 */
	public void showOtherNotify(Context context, String username, String toId, String ticker, Class<?> cls){
		boolean isAllow = CustomApplication.getInstance().getSpUtil().isAllowPushNotify();
		boolean isAllowVoice = CustomApplication.getInstance().getSpUtil().isAllowVoice();
		boolean isAllowVibrate = CustomApplication.getInstance().getSpUtil().isAllowVibrate();
		if(isAllow && currentUser!=null && currentUser.getUserID().equals(toId)){
			//同时提醒通知
			WeTalkNotifyManager.getInstance(context).showNotify(isAllowVoice,isAllowVibrate,R.drawable.ic_launcher, ticker,username, ticker.toString(),NewFriendsActivity.class);
		}
	}

}
